/* eslint-disable vue/no-template-shadow */
<template>
  <div class="index">
    <el-row>
      <el-col :span="7">
        <section class="left_wrap">
          <el-card class="box-card" style="position: relative;height: 277px;">
            <div slot="header" class="clearfix">
              <span>
                <i slot="prefix" class="el-icon-caret-bottom" />
                项目基础管理
                <i slot="suffix" class="el-icon-caret-bottom" />
              </span>
            </div>
            <div class="text item" style="margin-top: 14px;">
              <div class="item_name">
                <span>项目名称</span>
                <span>项目造价</span>
                <span>项目规模</span>
              </div>
              <div class="item_content">
                <span style="color:#e9d496">{{ profile.projectName }}</span>
                <span style="color:#40bcad">{{ profile.cost }}</span>
                <span style="color:#39d2e2">{{ profile.scale }}</span>
              </div>
              <div class="item_wrap">
                <ul class="wrodmain">
                  <li class="wrod">
                    <img src="../assets/images/dot.png" align="center">
                    建设单位：{{ profile.constructionOrganization }}
                  </li>
                  <li class="wrod">
                    <img src="../assets/images/dot.png" align="center">
                    设计单位：{{ profile.designOrganization }}
                  </li>
                  <li class="wrod">
                    <img src="../assets/images/dot.png" align="center">
                    施工单位：{{ profile.enforcementOrganization }}
                  </li>
                  <li class="wrod">
                    <img src="../assets/images/dot.png" align="center">
                    监理单位：{{ profile.supervisorOrganization }}
                  </li>
                </ul>
              </div>
            </div>
          </el-card>
          <el-card class="box-card" style="height: 242.8px;position: relative">
            <div slot="header" class="clearfix">
              <span>
                <i slot="prefix" class="el-icon-caret-bottom" />
                考勤管理
                <i slot="suffix" class="el-icon-caret-bottom" />
              </span>
            </div>
            <div class="text item" style="position: relative;top: -60px;">
              <div class="chart_wrap">
                <RingChart v-if="isRouterShow" :duty-info="dutyInfo" />
              </div>
              <div class="pieContent">
                <div class="item_wrap">
                  <span style="color:#4b8eb9;font-size:18px">{{ num }}</span>
                  <span style="color:#4b8eb9;font-size:15px">总人数</span>
                </div>
                <div class="item_wrap">
                  <span style="color:#e9e199;font-size:18px">{{ inNum }}</span>
                  <span style="color:#4b8eb9;font-size:15px">出勤人数</span>
                </div>
              </div>
            </div>
          </el-card>
        </section>
      </el-col>
      <el-col :span="10">
        <section class="center_wrap">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>
                <i slot="prefix" class="el-icon-caret-bottom" />
                视频管理
                <i slot="suffix" class="el-icon-caret-bottom" />
              </span>
            </div>
            <div class="text item" style="color:#fff;margin-top:10px">
              <div
                class="no-margin no-padding video"
                @mousemove="resetCloseTimer(videoPlayer)"
                @touchstart="resetCloseTimer(videoPlayer)"
              >
                <LivePlayer
                  v-loading="videoPlayer.bLoading"
                  :video-url="videoPlayer.url"
                  :poster="videoPlayer.poster"
                  :live="true"
                  :stretch="true"
                  :fluent="false"
                  :show-custom-button="false"
                  element-loading-text="加载中..."
                  element-loading-background="#000"
                  :loading.sync="videoPlayer.bLoading"
                />
              </div>
              <div
                v-show="videoPlayer.url && videoPlayer.bCloseShow"
                class="video-close"
                @click="closeVideo"
              >关闭</div>
              <div
                v-show="!videoPlayer.url && videoPlayer.bCloseShow"
                class="video-close"
                @click="selectChannel"
              >选择通道</div>
              <el-dialog
                append-to-body
                :close-on-click-modal="false"
                :visible.sync="handleViewShow"
                :title="title"
                width="850px"
              >
                <el-form ref="form" :inline="true" :model="form" size="small" label-width="67px">
                  <el-form-item>
                    <el-input v-model="form.value" clearable placeholder="请输入搜索内容" />
                  </el-form-item>
                  <el-select
                    v-model="form.type"
                    clearable
                    placeholder="类型"
                    class="filter-item"
                    style="width: 130px"
                  >
                    <el-option
                      v-for="item in queryTypeOptions"
                      :key="item.key"
                      :label="item.display_name"
                      :value="item.key"
                    />
                  </el-select>
                  <el-button
                    class="filter-item"
                    size="mini"
                    type="success"
                    icon="el-icon-search"
                    style="height: 30px;"
                    @click="handClickSearchBtn"
                  >搜索</el-button>
                </el-form>
                <br>
                <el-table
                  ref="channelTable"
                  v-loading="loading"
                  :data="channels"
                  :max-height="500"
                  :row-style="rowStyle"
                  element-loading-text="加载中..."
                  border
                  style="margin-top: -16px;"
                  @sort-change="sortChange"
                  @row-click="rowClick"
                >
                  <el-table-column
                    prop="name"
                    label="设备名称"
                    min-width="200"
                    show-overflow-tooltip
                    sortable="custom"
                    align="center"
                  />
                  <el-table-column
                    prop="ip"
                    label="IP地址"
                    min-width="200"
                    show-overflow-tooltip
                    sortable="custom"
                    align="center"
                  />
                  <el-table-column
                    prop="port"
                    label="端口"
                    min-width="200"
                    show-overflow-tooltip
                    sortable="custom"
                    align="center"
                  />
                  <el-table-column
                    prop="path"
                    label="路径"
                    min-width="200"
                    show-overflow-tooltip
                    sortable="custom"
                    align="center"
                  />
                </el-table>
                <div style="text-align: right;">
                  <el-pagination
                    layout="total,prev,pager,next"
                    :pager-count="5"
                    class="pull-right"
                    :total="total"
                    :page-size.sync="pageSize"
                    :current-page.sync="currentPage"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                  />
                </div>
                <div slot="footer" class="dialog-footer">
                  <el-button type="info" @click="handleCancelClickBtn">取消</el-button>
                </div>
              </el-dialog>
            </div>
          </el-card>
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>
                <i slot="prefix" class="el-icon-caret-bottom" />
                项目进度
                <i slot="suffix" class="el-icon-caret-bottom" />
              </span>
            </div>
            <div class="text item">
              <div class="setWrap">
                <el-steps
                  :active="active"
                  align-center
                  style="padding-bottom: 82px; padding-top: 42px;"
                >
                  <el-step
                    v-for="item in septList"
                    :key="item.index"
                    class="stepActive"
                    :title="item.label"
                    @click.native="stepClick(item.index)"
                  />
                </el-steps>
              </div>
            </div>
          </el-card>
        </section>
      </el-col>
      <el-col :span="7">
        <div class="right_wrap">
          <el-card class="box-card" style="position: relative;height: 277px;">
            <div slot="header" class="clearfix">
              <span>
                <i slot="prefix" class="el-icon-caret-bottom" />
                监测数据
                <i slot="suffix" class="el-icon-caret-bottom" />
              </span>
            </div>
            <div class="text item">
              <div class="gas_wrap">
                <div class="item_gascontent">
                  <span class="el-icon-platform-eleme" />
                  <span>二氧化碳</span>
                  <span>{{ profile.carbonDioxide }}</span>
                </div>
                <div class="item_gascontent">
                  <span class="el-icon-eleme" />
                  <span>一氧化碳</span>
                  <span>{{ profile.carbonMonoxide }}</span>
                </div>
                <div class="item_gascontent">
                  <span class="el-icon-s-help" />
                  <span>氧气</span>
                  <span>{{ profile.oxygen }}</span>
                </div>
              </div>
              <div class="gas_wrap">
                <div class="item_gascontent">
                  <span class="el-icon-upload" />
                  <span>硫化氢</span>
                  <span>{{ profile.sulfurettedHydrogen }}</span>
                </div>
                <div class="item_gascontent">
                  <span class="el-icon-s-promotion" />
                  <span>甲烷</span>
                  <span>{{ profile.methane }}</span>
                </div>
                <div class="item_gascontent">
                  <span class="el-icon-watch" />
                  <span>监测时间</span>
                  <span>{{ profile.monitorTime }}</span>
                </div>
              </div>
            </div>
          </el-card>
          <el-card class="box-card" style="height: 242.8px;position: relative">
            <div slot="header" class="clearfix">
              <span>
                <i slot="prefix" class="el-icon-caret-bottom" />
                设备管理
                <i slot="suffix" class="el-icon-caret-bottom" />
              </span>
            </div>
            <div class="text item" style="margin-top: 10px;">
              <el-scrollbar style="height:176px">
                <section id="table">
                  <el-table
                    style="width: 100%"
                    :max-height="600"
                    :data="tableData"
                    stripe
                    fit
                    :cell-style="{padding:'5px',}"
                    :header-cell-style="{background: '#11294b',color:'#fff'}"
                  >
                    <el-table-column prop="desc" label="名称" max-width="148" align="center" />
                    <el-table-column prop="onLine" label="在线数" max-width="145" align="center" />
                    <el-table-column prop="sum" max-width="145" align="center" label="总数" />
                  </el-table>
                </section>
              </el-scrollbar>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 请求后台数据接口调用
// import $ from 'jquery'
import LivePlayer from '@liveqing/liveplayer'
import { getDictDataList } from '@/api/index'
import { getVideoSearchList } from '@/api/index'
// import { getConfigUrl } from '@/api/index'
import { getVideoInfoList } from '@/api/sapientialSite/videoInfo'
import RingChart from '@/components/Echarts/RingChart'
// import PieChart from '@/components/Echarts/PieChart'
// import ClireChart from '@/components/Echarts/ClireChart.vue'
// import ExtremeChart from '@/components/Echarts/ExtremeChart'
import moment from 'moment'

// 导入
export default {
  name: 'Dashboard',
  // 传入的值
  components: {
    // 饼图
    RingChart,
    // // 环图
    // PieChart,
    // 极地坐标图
    // ExtremeChart,
    // // 环图
    // ClireChart,
    // eslint-disable-next-line vue/no-unused-components
    LivePlayer
  },
  data() {
    return {
      active: 0,
      projectParams: [],
      gasParams: [],
      septList: [],
      total: 0,
      channels: [],
      pageSize: 5,
      currentPage: 0,
      dutyInfo: {},
      profile: {
        projectName: '',
        cost: '',
        scale: '',
        constructionOrganization: '',
        designOrganization: '',
        enforcementOrganization: '',
        supervisorOrganization: '',
        carbonDioxide: '',
        carbonMonoxide: '',
        oxygen: '',
        sulfurettedHydrogen: '',
        methane: '',
        monitorTime: ''
      },
      status: '',
      form: {
        value: '',
        type: ''
      },
      loading: false,
      videoPlayer: {
        url: '',
        bLoading: false,
        timer: 0,
        bCloseShow: false,
        closeTimer: 0,
        protocol: ''
      },
      protocol: '',
      gasMonitor: {},
      handleViewShow: false,
      handleCloseShowView: false,
      handleSelectChannelShow: true,
      title: '',
      index: 1,
      newParams: [],
      num: '',
      inNum: '',
      isRouterShow: true,
      // extremedata: [],
      queryTypeOptions: [{ key: 'name', display_name: '名称' }],
      tableData: []
    }
  },
  watch: {
    offset: function() {
      return (this.currentPage - 1) * this.pagesize
    },
    status: {
      handler(newVal, oldVal) {
        this.initDictDataList(newVal)
      },
      deep: true
    }
  },
  created() {
    this.initWebSocket()
    // this.initDictDataList()
  },
  destroyed() {
    this.websock.close() // 离开路由之后断开websocket连接
    this.closeVideo() // 离开路由之前关闭rtmp视频流
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
      window.screen.width
    }
    this.protocol = this.getQueryString('protocol', '')
  },
  methods: {
    // 初始化websocket
    getQueryString(name, defVal = '') {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
      var r = window.location.search.substr(1).match(reg)
      if (r != null) {
        return unescape(r[2])
      }
      return defVal
    },
    initWebSocket() {
      const username = window.localStorage.getItem('username')
      const wsUri = process.env.VUE_APP_WS_API + '/socketServer/' + username
      // console.log(wsUri)
      this.websock = new WebSocket(wsUri)
      this.websock.onopen = this.websocketOnopen // 连接建立之后执行send方法发送数据 websocketsend(Data)//数据发送
      this.websock.onmessage = this.websocketOnmessage // 数据接收
      this.websock.onerror = this.websocketOnerror // 连接建立失败重连
      this.websock.onclose = this.websocketClose // 直接关闭
    },
    websocketOnopen() {
      console.log('WebSocket连接成功')
    },
    websocketOnerror(e) {
      this.initWebSocket()
    },
    websocketOnmessage(e) {
      // console.log(e)
      if (TypeError(e.data) === undefined) {
        console.log('数据不存在')
        return false
      }
      // 数据接收
      const params = JSON.parse(e.data)
      // console.log(params)
      if (params.attendance === undefined) {
        this.num = '——'
        this.inNum = '——'
        this.dutyInfo = {}
        return false
      } else {
        // console.log(params.attendance)
        this.dutyInfo = params.attendance
        // console.log(this.dutyInfo)
        // this.reload()
        // 考勤数据
        this.num = params.attendance.sum
        this.inNum = params.attendance.inNum
      }
      // 设备管理数据
      if (params.equipment === null) {
        this.tableData = []
      } else {
        this.tableData = params.equipment
      }
      // 项目基础信息
      if (params.projectInit === undefined) {
        this.profile.projectName = '——'
        this.profile.cost = '——'
        this.profile.scale = '——'
        this.profile.constructionOrganization = '——'
        this.profile.designOrganization = '——'
        this.profile.enforcementOrganization = '——'
        this.profile.supervisorOrganization = '——'
        return false
      } else {
        this.profile.projectName = params.projectInit.projectName
        this.profile.cost = params.projectInit.cost
        this.profile.scale = params.projectInit.scale
        this.status = params.projectInit.status
        this.profile.constructionOrganization =
          params.projectInit.constructionOrganization
        this.profile.designOrganization = params.projectInit.designOrganization
        this.profile.enforcementOrganization =
          params.projectInit.enforcementOrganization
        this.profile.supervisorOrganization =
          params.projectInit.supervisorOrganization
      }
      // 监测数据
      if (params.gasMonitor === undefined) {
        this.profile.carbonDioxide = '——'
        this.profile.carbonMonoxide = '——'
        this.profile.oxygen = '——'
        this.profile.sulfurettedHydrogen = '——'
        this.profile.methane = '——'
        this.profile.monitorTime = '——'
        return false
      } else {
        this.profile.carbonDioxide = params.gasMonitor.carbonDioxide
        this.profile.carbonMonoxide = params.gasMonitor.carbonMonoxide
        this.profile.oxygen = params.gasMonitor.oxygen
        this.profile.sulfurettedHydrogen = params.gasMonitor.sulfurettedHydrogen
        this.profile.methane = params.gasMonitor.methane
        this.profile.monitorTime = moment(
          new Date(params.gasMonitor.monitorTime)
        ).format('YYYY-MM-DD hh:mm:ss')
      }
    },
    websocketClose(e) {
      // 关闭
      console.log('断开连接', e)
    },
    // async reload() {
    //   this.isRouterShow = false
    //   await this.$nextTick()
    //   this.isRouterShow = true
    // },
    // 排序
    sortChange(data) {
      // console.log(data)
      this.sort = data.prop
      this.order = data.order === 'ascending' ? 'asc' : 'desc'
    },
    // 项目进度
    stepClick() {},
    initDictDataList(newVal) {
      // console.log('项目进度', newVal)
      // console.log('项目状态', Number(newVal))
      this.active = Number(newVal)
      getDictDataList().then(res => {
        this.septList = res.content
      })
    },
    // 搜索
    handClickSearchBtn() {
      const params = {
        page: 0,
        size: 10,
        sort: 'id,desc',
        value: this.form.value,
        type: this.form.type,
        name: this.form.value
      }
      getVideoSearchList(params)
        .then(res => {
          this.channels = res.content || []
          this.total = 3
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleCancelClickBtn() {
      this.form.type = ''
      this.form.value = ''
      this.queryTypeOptions = []
      this.handleViewShow = false
    },
    closeVideo() {
      if (!this.videoPlayer) {
        return
      }
      if (this.videoPlayer.closeTimer) {
        clearTimeout(this.videoPlayer.closeTimer)
        this.videoPlayer.closeTimer = 0
      }
      this.videoPlayer.bCloseShow = false
      this.videoPlayer.bloading = false
      this.videoPlayer.poster = ''
      this.videoPlayer.url = ''
    },
    selectChannel() {
      this.title = '选择通道'
      getVideoInfoList()
        .then(res => {
          this.channels = res.content || []
          this.total = 3
        })
        .catch(err => {
          console.log(err)
        })
      this.handleViewShow = true
    },
    handleSizeChange(val) {
      this.pagesize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    rowClick(row, event, column) {
      console.log('表格数据', row)
      var videoUrl = row.path
      console.log('播放路径')
      console.log(videoUrl)
      var protocol = 'RTMP'
      this.videoPlayer.protocol = protocol
      this.videoPlayer.poster = protocol === 'RTMP' ? '' : videoUrl
      this.$nextTick(() => {
        this.videoPlayer.url = videoUrl
        console.log('视频路径', this.videoPlayer.url)
      })
      this.resetCloseTimer(this.videoPlayer)
      this.handleViewShow = false
    },
    rowStyle({ row, rowIndex }) {
      if (row.status === 'on') {
        return 'cursor:pointer'
      }
      return 'cursor:pointer'
    },
    resetCloseTimer(videoPlayer) {
      videoPlayer.bCloseShow = true
      if (videoPlayer.closeTimer) {
        clearTimeout(videoPlayer.closeTimer)
      }
      videoPlayer.closeTimer = setTimeout(() => {
        videoPlayer.bCloseShow = false
      }, 2000)
    },
    beforeRouteEnter(to, from, next) {
      next(vm => {
        vm.protocol = vm.getQueryString('protocol', '')
      })
    },
    beforeRouteUpdate(to, from, next) {
      this.closeVideo()
      this.protocol = this.getQueryString('protocol', '')
      next()
    },
    beforeRouteLeave(to, from, next) {
      this.closeVideo()
      next()
    }
  }
}
</script>

<style lang="scss" scoped>
.index {
  padding: 10px 10px;
  background-color: #11294b;
  min-height: calc(100vh - 84px);
  .el-card {
    margin: 10px 7px 0px 7px;
    background-color: #19375b;
    border: 1px solid #19375b;
    border-radius: 5px;
    /deep/ .el-card__header {
      padding: 18px 10px;
      span {
        color: #549ac7;
        border: 1px solid #0f254a;
        padding: 5px;
        background-color: #0f254a;
        font-weight: 700;
      }
    }

    /deep/ .el-card__body {
      padding: 20px !important;
      margin-top: -25px;

      .item_name {
        display: flex;
        justify-content: space-between;
        color: #336699;
        align-items: center;
      }

      .item_content {
        display: flex;
        justify-content: space-between;
        padding-top: 15px;
        span {
          padding-right: 5px;
          font-size: 16px;
        }
      }

      .item_wrap {
        display: flex;
        flex-direction: column;
        .wrodmain {
          padding-left: 0px;
          .wrod {
            color: #336699;
            font-size: 15px;
            padding-top: 5px;
            list-style: none;
            margin-left: -5px;
          }
        }
      }

      .gas_wrap {
        display: flex;
        padding: 10px 0px;
        .item_gascontent {
          border-left: 1px solid #336699;
          border-right: 1px solid #336699;
          border-top: 1px solid #336699;
          width: 32%;
          border-radius: 10px;
          display: grid;
          flex-direction: column;
          align-items: center;
          padding-top: 5px;
          margin: 0px 3px;
          border-bottom: 2px solid aliceblue;
          text-align: center;
          span {
            padding: 5px;
            color: #fff;
            font-size: 14px;
          }
        }
      }

      .pieContent {
        display: flex;
        justify-content: center;
        .item_wrap {
          border-left: 1px solid #accfde;
          border-top: 1px solid #accfde;
          border-bottom: 1px solid #336699;
          border-right: 1px solid #336699;
          padding: 6px;
          border-radius: 10px;
          text-align: center;
          line-height: 21px;
          height: 55px;
          width: 120px;
          margin: 0px 15px 0px 15px;
        }
      }
    }
  }
}

.deviceWrap {
  color: #ffff;
  display: flex;
  list-style: none;
  justify-content: space-between;
}

.deviceContent {
  color: #ffff;
  display: flex;
  list-style: none;
  justify-content: space-between;
}

.video-close {
  position: absolute;
  top: 71px;
  right: 30.8%;
  color: white;
  font-size: 12px;
  padding: 2px 5px;
  cursor: pointer;
  border-radius: 2px;
  max-width: 120px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

/deep/ .video-wrapper {
  height: 448px;
  padding-bottom: 0px !important;
}
/deep/ .video-js .vjs-tech {
  position: absolute;
  top: -7px;
  left: 0;
  height: 102%;
}

.el-scrollbar {
  /deep/ .el-scrollbar__wrap {
    overflow-x: hidden;
    overflow-y: scroll;
    section {
      &#table {
        background-color: #19375b;
        /deep/ .el-table__row,
        .el-table__row--striped {
          background-color: #19375b;
          color: #fff;
        }
        /deep/ .el-table__empty-block {
          background-color: #2b354e;
        }

        /deep/ .el-table--striped .el-table__body tr.el-table__row--striped td {
          background-color: #19375b !important;
        }

        /deep/ .el-table__body tr:hover > td {
          background-color: #19375b !important;
        }

        /deep/ .el-table__body tr.current-row > td {
          background-color: #19375b !important;
        }

        /deep/ .el-table__empty-block {
          background-color: #19375b !important;
          span {
            color: #fff;
          }
        }

        /deep/ .table .el-table--group::after,
        .table .el-table--border::after,
        .el-table::before {
          content: '';
          position: absolute;
          background-color: #19375b;
          z-index: 1;
        }
      }
    }
  }
}

/deep/ .el-step.is-horizontal.stepActive {
  .el-step__head.is-finish {
    border-color: #339999;
    .el-step__line {
      // 当前步骤数横线样式设置
      color: #339999;
      .el-step__line-inner {
        width: 100% !important;
        border-width: 1px !important;
      }
    }
    // 当前步骤数圆圈样式设置
    .el-step__icon.is-text {
      color: #fff;
      background: #339999;
    }
  }
  .el-step__head.is-process {
    color: #549ac7;
    border-color: #549ac7;
    .el-step__line {
      // 当前步骤数横线样式设置
      color: #549ac7;
      .el-step__line-inner {
        width: 100% !important;
        border-width: 1px !important;
      }
    }
    // 当前步骤数圆圈样式设置
    .el-step__icon.is-text {
      color: #fff;
      background: #549ac7;
    }
  }
}
</style>
<style>
.el-step__title.is-finish {
  color: #339999;
}
.el-step__title.is-process {
  color: #549ac7;
}

#table .el-table th.is-leaf,
#table .el-table td {
  border-bottom: none !important;
}

.el-step__title.is-wait {
  color: #5380a7;
}

.el-dialog__header {
  text-align: center;
}
</style>
